package com.wcy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wcy.domain.SysUserRole;
import com.wcy.service.SysUserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wcy.mapper.SysUserMapper;
import com.wcy.domain.SysUser;
import com.wcy.service.SysUserService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

/**
 * <p>Title:SysUserServiceImpl.java</p >
 * <p>Description: </p >
 * <p>Copyright: 公共服务与应急管理战略业务本部 Copyright(c)2020</p >
 * <p>Date:2021/9/18 22:14</p >
 *
 * @author wcy (wangchaoyanga@mail.taiji.com.cn)
 * @version 1.0
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService{

    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private SysUserService sysUserService;

    @Override
    public Page<SysUser> findByPage(Page<SysUser> page, String mobile, String fullname) {
        Page<SysUser> pageData = page(page, new LambdaQueryWrapper<SysUser>()
                .like(!StringUtils.isEmpty(mobile), SysUser::getMobile, mobile)
                .like(!StringUtils.isEmpty(fullname), SysUser::getFullname, fullname)
        );
        List<SysUser> records = pageData.getRecords();
        if(!CollectionUtils.isEmpty(records)){
            for (SysUser record : records) {
                List<SysUserRole> roles = sysUserRoleService.list(new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getUserId, record.getId()));
                if(!CollectionUtils.isEmpty(roles)){
                    record.setRole_strings(roles.stream().map(sysUserRole -> sysUserRole.getRoleId().toString()).collect(Collectors.joining(",")));
                }
            }
        }
        return pageData;
    }

    @Override
    @Transactional
    public boolean addSysUser(SysUser sysUser) {
        // 加密密码
        sysUser.setPassword(passwordEncoder.encode(sysUser.getPassword()));
        save(sysUser);
        // 处理用户角色数据
        String role_strings=sysUser.getRole_strings();
        if(!StringUtils.isEmpty(role_strings)){
            String[] roleIds = role_strings.split(",");
            List<SysUserRole> sysUserRoleList=new ArrayList<>(roleIds.length);
            for (String roleId : roleIds) {
                SysUserRole sysUserRole=new SysUserRole();
                sysUserRole.setRoleId(Long.valueOf(roleId));
                sysUserRole.setUserId(sysUser.getId());
                sysUserRoleList.add(sysUserRole);
            }
            sysUserRoleService.saveBatch(sysUserRoleList);
        }
        return true;
    }

    @Override
    @Transactional
    public boolean updateSysUser(SysUser sysUser) {
        // 判断密码是否修改
        SysUser oldUser = sysUserService.getById(sysUser.getId());
        // 如果密码被修改则加密密码
        if(!oldUser.getPassword().equals(sysUser.getPassword())){
            sysUser.setPassword(passwordEncoder.encode(sysUser.getPassword()));
        }
        // 更新用户信息
        updateById(sysUser);
        // 删除用户原有角色信息
        sysUserRoleService.remove(new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getUserId,sysUser.getId()));
        // 新增用户角色信息
        String role_strings=sysUser.getRole_strings();
        if(!StringUtils.isEmpty(role_strings)){
            String[] roleIds = role_strings.split(",");
            List<SysUserRole> sysUserRoleList=new ArrayList<>(roleIds.length);
            for (String roleId : roleIds) {
                SysUserRole sysUserRole=new SysUserRole();
                sysUserRole.setRoleId(Long.valueOf(roleId));
                sysUserRole.setUserId(sysUser.getId());
                sysUserRoleList.add(sysUserRole);
            }
            sysUserRoleService.saveBatch(sysUserRoleList);
        }
        return true;
    }

    @Override
    @Transactional
    public boolean deleteSysUser(Long[] userIds) {
        // 首先删除附带的角色信息
        sysUserRoleService.remove(new LambdaQueryWrapper<SysUserRole>().in(SysUserRole::getUserId,Arrays.asList(userIds)));
        // 然后删除用户信息
        sysUserService.removeByIds(Arrays.asList(userIds));
        return true;
    }
}
